package com.hyphenate.easeui.ui;

import android.content.Intent;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.ResultReceiver;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.e.library.activity.EActivity;
import com.e.library.widget.ETitleBar;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.map.AddressService;
import com.hyphenate.easeui.map.GLocation;

/**
 * 谷歌定位
 * Created by e on 2017/8/15.
 * OnMapReadyCallback ,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener
 */

public class EaseGMapActivity extends EActivity implements OnMapReadyCallback,GoogleMap.OnMapClickListener{

    public static final String TAG = "GLocation";
    public static final String FORWARD = "forward";

    private ETitleBar titleBar;
    private TextView tv_region;
    private TextView tv_address;

    private GoogleMap mMap;
    private String mAddress;
    private double mLastLatitude;
    private double mLastLongitude;
    private GLocation gLocation;
    private ResultReceiver mReceiver = new ResultReceiver(new Handler(Looper.getMainLooper())){
        @Override
        protected void onReceiveResult(int resultCode, final Bundle bundle) {
            super.onReceiveResult(resultCode, bundle);

            if (resultCode == AddressService.RESULT_FAILURE) {
                final String msg = bundle.getString(AddressService.EXTRA_FAILURE);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toast(msg);
                    }
                });
            } else if(resultCode == AddressService.RESULT_SUCCESS) {
                String region = bundle.getString(AddressService.EXTRA_REGION);
                mAddress = bundle.getString(AddressService.EXTRA_ADDRESS);
                tv_region.setText(region);
                tv_address.setText(mAddress);
            }
        }
    };

    @Override
    protected int layout() {
        return R.layout.activity_gmap;
    }

    @Override
    protected void onActivityCreated(Bundle state) {


        tv_region = (TextView) findViewById(R.id.tv_region);
        tv_address = (TextView) findViewById(R.id.tv_address);
        titleBar = (ETitleBar) findViewById(R.id.title_bar);
        titleBar.setOnForwardListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendLocation();
            }
        });

        String text = getIntent().getStringExtra(FORWARD);
        if(!TextUtils.isEmpty(text)) {
            titleBar.setForwardText(text);
        }

        gLocation = new GLocation(this){
            @Override
            protected void successful(double lng, double lat) {
                super.successful(lng, lat);
                fetchAddress(lng,lat);
            }

            @Override
            protected void failure() {
                super.failure();
            }
        };

        gLocation.setZoom(15);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    private void fetchAddress(double lng, double lat){

        mLastLatitude = lat;
        mLastLongitude = lng;
        mMap.clear();
        LatLng latLng = new LatLng(mLastLatitude, mLastLongitude);
        mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_location_marker)));
        if (!Geocoder.isPresent()){
            return;
        }

        Intent intent = new Intent(EaseGMapActivity.this, AddressService.class);
        intent.putExtra(AddressService.EXTRA_RECEIVER,mReceiver);
        intent.putExtra(AddressService.EXTRA_LONGITUDE,lng);
        intent.putExtra(AddressService.EXTRA_LATITUDE,lat);
        startService(intent);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        mMap.setTrafficEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        mMap.setOnMapClickListener(this);
        gLocation.onMapReady(mMap);
    }

    @Override
    public void onMapClick(LatLng latLng) {
        fetchAddress(latLng.longitude,latLng.latitude);
    }

    @Override
    public void onStart() {
        super.onStart();
        gLocation.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        gLocation.onStop();
    }

    @Override
    public void onPause() {
        super.onPause();
        gLocation.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        gLocation.onResume();
    }

    public void sendLocation() {
		Intent intent = this.getIntent();
		intent.putExtra("latitude", mLastLatitude);
		intent.putExtra("longitude", mLastLongitude);
		intent.putExtra("address", mAddress);
		this.setResult(RESULT_OK, intent);
		defaultFinish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        gLocation.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        gLocation.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }
}
